package com.learn.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.learn.core.domain.LChapter;
import com.learn.core.mapper.LChapterMapper;
import com.learn.core.service.ILChapterService;
import com.learn.framework.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @auther CodeGenerator
 * @create 2021-03-13 19:41:29
 * @describe 章节表服务实现类
 */
@Service
public class LChapterServiceImpl extends BaseServiceImpl<LChapterMapper, LChapter> implements ILChapterService {

    @Autowired
    LChapterMapper lChapterMapper;

    @Override
    public List<LChapter> queryLChapterAll(QueryWrapper<LChapter> queryWrapper) {
        List<LChapter> treeMenus =new ArrayList<>();
        List<LChapter> lChapterList = lChapterMapper.selectList(queryWrapper);
        // 查询树结构
        for(LChapter lChapter : getDictTypeNode(lChapterList)) {
            lChapter=buildChilTree(lChapter,lChapterList);
            treeMenus.add(lChapter);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private LChapter buildChilTree(LChapter pNode,List<LChapter> lChapterList){
        List<LChapter> lChapters =new ArrayList<>();
        for(LChapter menuNode : lChapterList) {
            if(menuNode.getChapterItem() == pNode.getChapterId()) {
                lChapters.add(buildChilTree(menuNode,lChapterList));
            }
        }
        pNode.setlChilLChapter(lChapters);
        return pNode;
    }

    //获取根节点
    private List<LChapter> getDictTypeNode(List<LChapter> lChapters) {
        List<LChapter> lChapterList =new  ArrayList<LChapter>();
        for(LChapter lChapter : lChapters) {
            if(lChapter.getChapterItem() == 0) {
                lChapterList.add(lChapter);
            }
        }
        return lChapterList;
    }
}
